package com.xiumiing.net.base.net.util;

import android.net.ParseException;

import com.google.gson.JsonParseException;
import com.xiumiing.net.base.uitls.JSONUtils;

import org.json.JSONException;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import okhttp3.RequestBody;

import static com.xiumiing.net.base.net.util.DuckHttpException.CONNECT_EXCEPTION;
import static com.xiumiing.net.base.net.util.DuckHttpException.ILLEGAL_ARGUMENT_EXCEPTION;
import static com.xiumiing.net.base.net.util.DuckHttpException.PARSE_EXCEPTION;
import static com.xiumiing.net.base.net.util.DuckHttpException.SOCKET_TIMEOUT_EXCEPTION;
import static com.xiumiing.net.base.net.util.DuckHttpException.UNKNOWN_HOST_EXCEPTION;
import static com.xiumiing.net.base.net.util.DuckHttpException.UN_KNOW_EXCEPTION;

/**
 * @author guguofeng
 * @desc 网络请求帮助类
 * @date 2019/3/13
 * @Copyright: 武汉市追忆那年网络科技有限公司
 */
public class HttpUtils {

    /**
     * map转body
     *
     * @param obj
     * @return
     */
    public static RequestBody getBodyParams(Object obj) {
        RequestBody requestBody = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=utf-8"), JSONUtils.toJson(obj));
        return requestBody;
    }


    /**
     * @param e
     * @return
     */
    public static DuckHttpException handleNetThrowable(Throwable e) {
        String error;
        //网络超时
        if (e instanceof SocketTimeoutException) {
            error = "网络连接异常，超时。";
            return new DuckHttpException(SOCKET_TIMEOUT_EXCEPTION, error, e);
        } //均视为网络错误
        else if (e instanceof ConnectException) {
            error = "没有网了，请检查网络是否连接。";
            return new DuckHttpException(CONNECT_EXCEPTION, error, e);
        }//均视为解析错误
        else if (e instanceof JsonParseException
                || e instanceof JSONException
                || e instanceof ParseException) {
            error = "服务器异常，请稍后再试！";
            return new DuckHttpException(PARSE_EXCEPTION, error, e);
        } else if (e instanceof UnknownHostException) {
            error = "网络连接异常，服务器错误。";
            return new DuckHttpException(UNKNOWN_HOST_EXCEPTION, error, e);
        } else if (e instanceof IllegalArgumentException) {
            error = "程序错误，非法参数异常。";
            return new DuckHttpException(ILLEGAL_ARGUMENT_EXCEPTION, error, e);
        } else {
            error = "未知错误。";
            return new DuckHttpException(UN_KNOW_EXCEPTION, error, e);
        }
    }
}